﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using Common.UniversityLibraryDataSetTableAdapters;
using System.Data;
using System.Data.SqlClient;

namespace Provider
{
    public class Provider
    {
        UniversityLibraryDataSet libraryDataSet = new UniversityLibraryDataSet();
        
        SqlDataAdapter[] libraryDataAdapters;

        DataTable[] libraryTables;
        string[] TablesName;

        SourceType dataType;
        string targetFile;

        public Provider() { }

        public UniversityLibraryDataSet GetAllData(SourceType dataType, string targetFile)
        {
            this.dataType = dataType;
            this.targetFile = targetFile;

            if (this.dataType == SourceType.XML)
            {
                this.libraryDataSet.ReadXml(this.targetFile);
                return this.libraryDataSet;
            }

            this.libraryTables = new DataTable[]
            {
                this.libraryDataSet.Items,
                this.libraryDataSet.Authors,
                this.libraryDataSet.Books,
                this.libraryDataSet.Borrows,
                this.libraryDataSet.Copies,
                this.libraryDataSet.Magazines,
                this.libraryDataSet.Articles,
                this.libraryDataSet.ArticlesInMagazines,
                this.libraryDataSet.Users
            };
            this.TablesName = new string[] {"Items","Authors","Books", 
                "Borrows","Copies", "Magazines","Articles","ArticlesInMagazines","Users"};
            libraryDataAdapters = new SqlDataAdapter[this.TablesName.Length];
            SqlConnection con = new SqlConnection(this.targetFile);

            for (int i = 0; i < TablesName.Length; i++)
            {
                this.libraryDataAdapters[i] =
                    new SqlDataAdapter("SELECT * FROM "+this.TablesName[i], con);
                SqlCommandBuilder combld = new SqlCommandBuilder(this.libraryDataAdapters[i]);
            }

            try
            {
                for (int i = 0; i < this.libraryDataAdapters.Length; i++)
                {
                    libraryDataAdapters[i].Fill(this.libraryTables[i]);
                }
            }
            catch
            {
                this.libraryDataSet = null;
            }

            return this.libraryDataSet;
        }

        public void UpdateAllData()
        {
            if (this.dataType == SourceType.XML)
            {
                this.libraryDataSet.WriteXml(this.targetFile);
                return;
            }

            for (int i = 0; i < this.libraryDataAdapters.Length; i++)
            {
                this.libraryDataAdapters[i].Update(this.libraryTables[i]);
            }
        }
    }
}
